import os
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from os.path import isfile, join
import pyautogui
import sys

#目前支持txt、sql等utf-8格式文件
# 针对某个文件修改
def replace_file(old_content):
    #选择文件
    file_path = select_file()
    old_content = get_delay1()
    print(f"被替换的值旧的:{old_content}")
    new_content = get_delay2()
    print(f"替换的值:{new_content}")
    try:
        with open(file_path,'r+',encoding='utf-8') as f:
            oldcontent = f.read()
        content = oldcontent.replace(old_content,new_content)
        with open(file_path,'w+',encoding='utf-8') as f:
            f.write(content)
    except Exception as e:
        print(e)


#针对某个文件夹下文件修改
def replace_files():
    #选择文件夹
    dir_path=select_folder()
    old_content=get_delay1()
    print(f"被替换的值旧的:{old_content}")
    new_content=get_delay2()
    print(f"替换的值:{new_content}")
    for root, dirs, files in os.walk(dir_path):
        #遍历当前目录所有文件
        for file in files:
            file_path=os.path.join(root,file)
            try:
                with open(file_path, 'r+', encoding='utf-8') as f:
                    oldcontent = f.read()
                content = oldcontent.replace(old_content, new_content)
                with open(file_path, 'w+', encoding='utf-8') as f:
                    f.write(content)
            except Exception as e:
                print(e)
    message()


def select_folder():
    root=tk.Tk()
    root.withdraw() #隐藏主窗口
    file_path=filedialog.askdirectory() #打开文件夹选择对话框
    print(f"当前选择文件夹路径是：{file_path}")
    return file_path

def select_file():
    root=tk.Tk()
    root.withdraw() #隐藏主窗口
    file=filedialog.askopenfilename()#显示选择文件对话框
    print(f"当前选择的文件是：{file}")
    return file

#输入内容
def get_delay1():
    s=pyautogui.prompt(text='请输入被替换的值旧的',title='替换内容',default=1)
    print(s)
    return s
def get_delay2():
    s=pyautogui.prompt(text='请输入替换的值',title='替换内容',default=1)
    print(s)
    return s

def message():
    root=tk.Tk()
    root.withdraw()
    messagebox.showinfo("弹框","替换成功")
# 针对某个文件修改 目前支持txt、sql等utf-8格式文件
# replace_file('./txt/test.txt','nihao2','nihao3')
#针对某个文件夹下文件修改
# replace_files('C:/code/Python/autoClick/txt','nihao2','nihao')
#打开本地文件夹
# select_folder()
# replace_files()
# replace_file('nihao')

#测试输入内容
# get_delay()
if __name__ == '__main__':
    replace_files()